import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Router } from '@angular/router';

import { AuthService } from '../auth/auth.service';

/**
 * 登录的路由守卫
 */
@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private authService: AuthService) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    if (this.authService.currentUser == null) {
      this.router.navigate(['/login'], { queryParams: { redirectUrl: encodeURIComponent(state.url) } });
      return false;
    } else {
      return true;
    }
  }
}
